package baseFx.tests.common.config;

import baseFx.common.config.ConfigFactory;
import baseFx.common.config.ConfigReader;
import baseFx.common.config.MapConfig;
import baseFx.common.config.Name;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ConfigFactoryTests {
    @Test
    public void 普通使用() {
        ConfigFactory.addReader(new ConfigReader() {
            @Override
            public String read(String namespace, String name) {
                if ("name".equalsIgnoreCase(name)) {
                    return "zhangsan";
                }
                if ("id".equalsIgnoreCase(name)) {
                    return "123456";
                }
                return null;
            }

            @Override
            public List<String> getNames(String namespace) {
                return null;
            }
        });
        Conf conf = ConfigFactory.get(Conf.class);
        Assert.assertEquals(conf.name(), "zhangsan");
    }

    @Test
    public void 自动实现MapConfig() {
        ConfigFactory.addReader(new ConfigReader() {
            @Override
            public String read(String namespace, String name) {
                if ("name".equalsIgnoreCase(name)) {
                    return "zhangsan";
                }
                if ("id".equalsIgnoreCase(name)) {
                    return "123456";
                }
                return null;
            }

            @Override
            public List<String> getNames(String namespace) {
                if ("test".equalsIgnoreCase(namespace)) {
                    return Arrays.asList("name", "id");
                }
                return null;
            }
        });
        Conf conf = ConfigFactory.get(Conf.class);
        Assert.assertEquals(conf.name(), "zhangsan");
        Assert.assertEquals(conf.getConfigValue("id"), "123456");
        List<String> names = conf.getConfigNames();
        Assert.assertEquals(2, names.size());
        for (String name : names) {
            System.out.println(conf.getConfigValue(name));
        }
    }

    @Test
    public void 默认返回值() {
        ConfigFactory.addReader(new ConfigReader() {
            @Override
            public String read(String namespace, String name) {
                return null;
            }

            @Override
            public List<String> getNames(String namespace) {
                return null;
            }
        });
        Conf conf = ConfigFactory.get(Conf.class);
        Assert.assertEquals(conf.def(), "default");
        Assert.assertEquals(conf.def(1), "default_1");
    }

    @Name("test")
    public interface Conf extends MapConfig {
        String name();

        default String def() {
            return "default";
        }

        default String def(Integer num) {
            return def() + "_" + num;
        }
    }
}
